﻿using ocmctr;
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace AutoKey
{
    public partial class Form1 : Form
    {
        public static UmfCtr umf=null;
        public static int is_auto = 1;
         bool umflink = false;
        public Form1()
        {

            InitializeComponent();

            if (umf == null) {
                umf = new UmfCtr();
                checkDevThread();
            }
            try
            {
                umf.startRead();
                is_auto = 1;
            }
            catch (Exception e) {
                MessageBox.Show("加密key"+e.Message.ToString());
            }
            finally
            {
                is_auto = 0;
            }


          
            }
        private void checkDevThread()
        {
            ThreadPool.QueueUserWorkItem(checkUmf, "");
        }
        private void closeDev()
        {
            try
            {
                Thread.Sleep(200);
                StopAutoRead();
                Thread.Sleep(200);
                umf.closeDev();
            }
            catch (Exception ex)
            {

            }
        }
        public void Reconncet()
        {
            closeDev();
            if (umf.openDev(0, 0, 0))
            {
                umflink = true;
                StartAutoRead();
            }
            else
            {
                if (umf.openDev(0, 0, 0))
                {
                    umflink = true;
                    StartAutoRead();
                }
                
            }
        }
        private void checkUmf(object state)
        {
            bool res = false;
            while (!umflink)
            {
                try
                {
                    res = umf.openDev(0, 0, 0);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                }
                if (res)
                {
                    umflink = true;
                }
                Thread.Sleep(1000);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            StopAutoRead();
        }

        private void StopAutoRead() {
            if (is_auto == 1)
            {
                umf.stopRead();
            }
            is_auto = 0;
            status.Text = "关闭";
            status.ForeColor = Color.Black;
        }
        private void StartAutoRead()
        {
            if (is_auto == 0)
            {
                umf.startRead();
            }
            is_auto = 1;
            status.Text = "开启";
            status.ForeColor = Color.Red;
        }

        private void reconn_Click(object sender, EventArgs e)
        {
            Reconncet();
        }

        private void start_Click(object sender, EventArgs e)
        {
            StartAutoRead();
        }
    }
}
